package com.yykj.order.center.server.util;

import java.io.*;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {
    public static boolean isBlank(String str) {
        return str == null || "".equals(str);
    }

    public static boolean isNotBlank(String str) {
        return !isBlank(str);
    }

    public static String getMd5ByFile(File file) {
        if (!file.isFile()) {
            return null;
        }

        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] bytes = digest.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String s = Integer.toHexString(b & 0xFF);
            if (s.length() == 1) {
                s = "0" + s;
            }
            sb.append(s);
        }
        return sb.toString();
    }

    public static String getMd5ByByte(byte[] b) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] digest = md5.digest(b);
            return new BigInteger(1, digest).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /*
     * public static void fileChannelCopy(File s, File t) { if (s == null ||
     * !s.exists()) { return; } FileInputStream fi = null; FileOutputStream fo =
     * null; FileChannel in = null; FileChannel out = null; try { fi = new
     * FileInputStream(s); fo = new FileOutputStream(t); in = fi.getChannel();
     * out = fo.getChannel(); in.transferTo(0, in.size(), out); } catch
     * (IOException e) { e.printStackTrace(); throw new RuntimeException();
     *
     * } finally { try { fi.close(); in.close(); fo.close(); out.close(); }
     * catch (IOException e) { e.printStackTrace(); throw new
     * RuntimeException(); } } }
     */

    public static void fileChannelCopy(File s, File t) {
        if (s == null || !s.exists()) {
            return;
        }
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(s));
            bos = new BufferedOutputStream(new FileOutputStream(t));
            int len = 0;
            byte[] b = new byte[1024];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void deleteFolder(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (file.isDirectory()) {
            File[] listFiles = file.listFiles();
            if (listFiles.length == 0) {
                file.delete();
                return;
            }
            for (File listFile : listFiles) {
                deleteFolder(listFile.getPath());
            }
            file.delete();
        } else {
            file.delete();
        }
    }

    public static long total = 0;

    public static void deleteFolderBySize(String path, long max) {
        if (total >= max) {
            return;
        }
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (file.isDirectory()) {
            File[] listFiles = file.listFiles();
            if (listFiles.length == 0) {
                file.delete();
                return;
            }
            for (File listFile : listFiles) {
                deleteFolderBySize(listFile.getPath(), max);
            }
            if (file.getName().endsWith("txt")) {

            }

        } else {
            total += file.length();
        }
        file.delete();
        File file2 = new File(file.getPath() + ".txt");
        if (file2.exists()) {
            file.delete();
        }
    }

    // strDate="19791108" 返回年龄,异常就返回 0
    public static int getAge(String strDate) {
        if (StringUtil.isBlank(strDate) || "0000-00-00".equals(strDate)) {
            return 0;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date birthDay = null;
        try {
            birthDay = sdf.parse(strDate);
        } catch (ParseException e) {
            return 0;
        }
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth)
                    age--;
            } else {
                age--;
            }
        }
        return age;
    }

    /*
     * 获取当前时间戳,单位:秒
     *
     * @return long
     */
    public static int getCurrentTime() {
        return (int) (System.currentTimeMillis() / 1000);
    }

    public static String timeStampToDate(String s) {
        if (StringUtil.isBlank(s)) {
            return "0";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        long lt = new Long(s);
        Date date = new Date(lt);
        return simpleDateFormat.format(date);
    }

    public static String timeStampToDate(String s, String format) {
        try {
            if (StringUtil.isBlank(s)) {
                return "0";
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            long lt = new Long(s);
            Date date = new Date(lt);
            return simpleDateFormat.format(date);
        } catch (Exception e) {
        }
        return "0";
    }

    public static String timeStamp2DateFormat(String seconds, String format) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds + "000")));
    }

    public static int dateToTimeStamp(String s, String formatStr) {
        if (StringUtil.isBlank(s)) {
            return 0;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
            return (int) (sdf.parse(s).getTime() / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static int dateToTimeStamp(String s) {
        return dateToTimeStamp(s, "yyyy-MM-dd");
    }

    public static void main(String[] args) {
        // yyyy-MM-dd HH:mm:ss
        //System.out.println(getTomorrow());
        String[] birthAndSexByIdNo = getBirthAndSexByIdNo("321002199407076410");


        System.out.println(birthAndSexByIdNo[0] + "---" + birthAndSexByIdNo[1]);

    }

    public static String getRandom() {
        int max = 100;
        int min = 1;
        Random random = new Random();
        return (random.nextInt(max) % (max - min + 1) + min) + "";
    }

    /**
     * 复制一个目录及其子目录、文件到另外一个目录
     *
     * @param src
     * @param dest
     * @throws IOException
     */
    public static void copyFolder(File src, File dest) {
        try {
            if (src.isDirectory()) {
                if (!dest.exists()) {
                    dest.mkdir();
                }
                String files[] = src.list();
                for (String file : files) {
                    File srcFile = new File(src, file);
                    File destFile = new File(dest, file);
                    // 递归复制
                    copyFolder(srcFile, destFile);
                }
            } else {
                InputStream in = new FileInputStream(src);

                OutputStream out = new FileOutputStream(dest);

                byte[] buffer = new byte[1024];

                int length;

                while ((length = in.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                }
                in.close();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @date: 2018年6月14日
     * @param lISTENER_FILE_PATH
     * @return: void
     * @author: xuad
     * @version:
     */
    static long temp = 30 * 24 * 60 * 60 * 1000L;


    /**
     * 递归删除文件夹内超过15天的文件
     *
     * @param file
     */

    public static void deleteFolder15(File file) {
        File[] listFiles = file.listFiles();
        for (File listFile : listFiles) {
            if (listFile.isDirectory()) {
                deleteFolder15(listFile);
            } else {
                long lastModified = listFile.lastModified();
                if (System.currentTimeMillis() - lastModified > 60 * 60 * 24 * 15 * 1000) {// 已经存在15天之前的日志,删除
                    listFile.delete();
                }
            }
        }
    }

    /*
     * 获取文件创建时间
     */
    public static long getCreateTime(String filePath) {
        try {
            Path path = Paths.get(filePath);
            BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class,
                    LinkOption.NOFOLLOW_LINKS);
            return basicview.readAttributes().creationTime().toMillis();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 调用cmd
     */
    public static void call(String command) {
        String cmd = "cmd /c " + command;
        System.out.println("开始调用cmd:" + cmd);
        try {
            Process ps = Runtime.getRuntime().exec(cmd);
            InputStream in = ps.getInputStream();
            in.read();
            in.close();
            ps.destroy();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public static String getMd5ByString(String info) {
        try {
            // 获取 MessageDigest 对象，参数为 MD5 字符串，表示这是一个 MD5 算法（其他还有 SHA1 算法等）：
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            // update(byte[])方法，输入原数据
            // 类似StringBuilder对象的append()方法，追加模式，属于一个累计更改的过程
            md5.update(info.getBytes("UTF-8"));
            // digest()被调用后,MessageDigest对象就被重置，即不能连续再次调用该方法计算原数据的MD5值。可以手动调用reset()方法重置输入源。
            // digest()返回值16位长度的哈希值，由byte[]承接
            byte[] md5Array = md5.digest();
            // byte[]通常我们会转化为十六进制的32位长度的字符串来使用,本文会介绍三种常用的转换方法
            return bytesToHex(md5Array);
        } catch (Exception e) {
            return "";
        }
    }

    private static String bytesToHex(byte[] md5Array) {
        StringBuilder strBuilder = new StringBuilder();
        for (int i = 0; i < md5Array.length; i++) {
            int temp = 0xff & md5Array[i];
            String hexString = Integer.toHexString(temp);
            if (hexString.length() == 1) {// 如果是十六进制的0f，默认只显示f，此时要补上0
                strBuilder.append("0").append(hexString);
            } else {
                strBuilder.append(hexString);
            }
        }
        return strBuilder.toString();
    }

    public static int string2int(String str) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * 返回今天日期,20190101
     */
    public static String getTodayChekcNo() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(cal.getTime());
    }

    /**
     * 返回今天日期,20190101
     */
    public static String getToday() {
        return getDate(0);
    }

    public static String getDate(int day) {
        Calendar cal = Calendar.getInstance();
        if (day != 0) {
            cal.add(Calendar.DATE, day);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    /**
     * 返回明天,20190101
     */
    public static String getTomorrow() {
        return getDate(1);
    }

    /**
     * 返回后天,20190101
     */
    public static String getAfterTomorrow() {
        return getDate(2);
    }




    public static String getAccessionNumberRegular(String accessionNumber) {
        try {
            String pattern = "[0-9]+$";
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(accessionNumber);
            if (m.find()) {
                return m.group(0);
            }
        } catch (Exception e) {
        }

        return accessionNumber;
    }

    public static int getAccessionNumberGenerate(String accessionNumber) {
        accessionNumber = getAccessionNumberRegular(accessionNumber);
        try {
            int year = string2int(accessionNumber.substring(0, 4));
            if (year >= 2019 && year <= 2029) {
                //判断是 1 还是 2
                try {
                    int month = string2int(accessionNumber.substring(4, 6));//以年开头,但是没有月,1
                    if (month >= 0 && month <= 12) {//有月,再判断日
                        int day = string2int(accessionNumber.substring(6, 8));
                        if (day >= 0 && day <= 31) {
                            return 1;
                        }
                    }
                } catch (Exception e) {
                }
                return 2;
            }
        } catch (Exception e) {
            //报错说明不足4位,再判断是否是 3,7
        }
        try {
            int year = string2int(accessionNumber.substring(0, 2));//年 前2位
            if (year >= 19 && year <= 29) {
                return 7;
            }
            return 3;
        } catch (Exception e) {
            //报错说明不足2位,直接就是3
            return 3;
        }
    }

    

    public static String getMapValue(Map<String, Object> map, String key) {
        return map.get(key) == null ? "" : map.get(key).toString();
    }

    public static int getMapValueInt(Map<String, Object> map, String key) {
        return StringUtil.string2int(getMapValue(map, key));
    }

    public static String timeStamp2Date(String seconds) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date(Long.valueOf(seconds + "000")));
    }

    public static String timeStamp2Date(String seconds, String format) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds + "000")));
    }

    public static final String UTF8_BOM = "\uFEFF";

    public static String removeUTF8BOM(String s) {
        if (s.startsWith(UTF8_BOM)) {
            s = s.substring(1);
        }
        return s;
    }

    public static String getAgeUnit(String age, String ageUnitStr) {
        // 年(0)、月(1)、周(2)、天(3)
        int ageUnit = StringUtil.string2int(ageUnitStr);
        ageUnitStr = "岁";
        switch (ageUnit) {
            case 1:
                ageUnitStr = "月";
                break;
            case 2:
                ageUnitStr = "周";
                break;
            case 3:
                ageUnitStr = "天";
                break;
        }
        return StringUtil.string2int(age) + ageUnitStr;
    }

    /**
     * 常用文件的文件头如下：(以前六位为准) JPEG (jpg)，文件头：FFD8FF PNG (png)，文件头：89504E47 GIF
     * (gif)，文件头：47494638 TIFF (tif)，文件头：49492A00 Windows Bitmap (bmp)，文件头：424D
     * CAD (dwg)，文件头：41433130 Adobe Photoshop (psd)，文件头：38425053 Rich Text
     * Format (rtf)，文件头：7B5C727466 XML (xml)，文件头：3C3F786D6C HTML
     * (html)，文件头：68746D6C3E Email [thorough only]
     * (eml)，文件头：44656C69766572792D646174653A Outlook Express
     * (dbx)，文件头：CFAD12FEC5FD746F Outlook (pst)，文件头：2142444E MS Word/Excel
     * (xls.or.doc)，文件头：D0CF11E0 MS Access (mdb)，文件头：5374616E64617264204A
     * WordPerfect (wpd)，文件头：FF575043 Postscript
     * (eps.or.ps)，文件头：252150532D41646F6265 Adobe Acrobat
     * (pdf)，文件头：255044462D312E Quicken (qdf)，文件头：AC9EBD8F Windows Password
     * (pwl)，文件头：E3828596 ZIP Archive (zip)，文件头：504B0304 RAR Archive
     * (rar)，文件头：52617221 Wave (wav)，文件头：57415645 AVI (avi)，文件头：41564920 Real
     * Audio (ram)，文件头：2E7261FD Real Media (rm)，文件头：2E524D46 MPEG
     * (mpg)，文件头：000001BA MPEG (mpg)，文件头：000001B3 Quicktime (mov)，文件头：6D6F6F76
     * Windows Media (asf)，文件头：3026B2758E66CF11 MIDI (mid)，文件头：4D546864
     */

    public static boolean checkImageFileBytes(byte[] b) {
        String xxx = bytesToHexString(b).toUpperCase().substring(0, 10);
        if (xxx.contains("FFD8FF") || xxx.contains("89504E47") || xxx.contains("49492A00")) {
            return true;
        }
        return false;
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }


    public static <T> String hashSet2CommaStr(HashSet<T> ids) {
        StringBuilder sb = new StringBuilder();
        for (T id : ids) {
            sb.append(id).append(",");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }


    public static String getMonthFirstDay() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
        return format.format(c.getTime());
    }

    //以,分割的字符串,去重,输出'',分割的字符串,用于sql
    public static String getCommaSetString(String str) {
        HashSet<String> strSet = new HashSet<String>();
        String[] split = str.split(",");

        for (String splitz : split) {
            splitz = splitz.trim();
            if (!StringUtil.isBlank(splitz) && splitz.length() > 0 && !"0".equals(splitz)) {
                strSet.add(splitz);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (String strz : strSet) {
            sb.append("'").append(strz).append("',");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    //以,分割的字符串,去重,分割的字符串
    public static String getCommaSetStringUnS(String str) {
        HashSet<String> strSet = new HashSet<String>();
        String[] split = str.split(",");

        for (String splitz : split) {
            splitz = splitz.trim();
            if (!StringUtil.isBlank(splitz) && splitz.length() > 0 && !"0".equals(splitz)) {
                strSet.add(splitz);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (String strz : strSet) {
            sb.append(strz).append(",");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    //以,分割的字符串,去重,分割的字符串
    public static String getCommaSetStringUnSTree(String str) {
        LinkedList<String> strings = new LinkedList<>();

        String[] split = str.split(",");

        for (String splitz : split) {
            splitz = splitz.trim();
            if (!StringUtil.isBlank(splitz) && splitz.length() > 0 && !strings.contains(splitz)) {
                strings.add(splitz);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (String strz : strings) {
            sb.append(strz).append(",");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    //以,分割的字符串,去重,输出'',分割的字符串,用于sql
    public static String getCommaSetStringForInt(String str) {
        HashSet<String> strSet = new HashSet<>();
        String[] split = str.split(",");
        for (String splitz : split) {
            splitz = splitz.trim();

            if (!StringUtil.isBlank(splitz) && splitz.length() > 0) {
                strSet.add(StringUtil.string2int(splitz) + "");
            }
        }
        StringBuilder sb = new StringBuilder();
        for (String strz : strSet) {
            sb.append(strz).append(",");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }


    public static String getArrayListCommaStringForInt(ArrayList<Integer> ids) {
        StringBuilder sb = new StringBuilder();
        for (int id : ids) {
            sb.append(id).append(",");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }


    //或者俩个int的百分比
    public static String getPreforInt(int count, int total) {
        if (count == 0 || total == 0) {
            return "0";
        }
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        return numberFormat.format((float) count / (float) total * 100);//所占百分比
    }

    final static String base = "123456789abcdefghjkmnpqrstuvwxyz";
    final static int passwordLength = 4;//二维码密码长度

    public static String getQrcodePassword(int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        String s = sb.toString();
        if (checkPasword(s)) {
            return s;
        }
        return getQrcodePassword(length);
    }

    //是否含数字和字母
    public static boolean checkPasword(String password) {
        String[] split = password.split("");
        boolean hasNum = false;
        ;
        boolean hasChar = false;
        for (String splitz : split) {
            try {
                Integer.parseInt(splitz);
                hasNum = true;
            } catch (Exception e) {//数字格式化成功就是数字 失败就是字母
                hasChar = true;
            }
        }
        return hasNum && hasChar;
    }

    public static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;

    }

    public static String date2TimeStamp(String strDate, String format) {
        if (StringUtil.isBlank(strDate)) {
            return "";
        }
        String res = System.currentTimeMillis() / 1000 + "";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date;
        try {
            date = sdf.parse(strDate);
            long ts = date.getTime() / 1000;
            res = String.valueOf(ts);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return res;
    }


    static long dateSecond = 86400l;

    //获取多少天的秒
    public static long getSecondByDate(int date) {
        return dateSecond * date;
    }

    static int minuteSecond = 60;

    //获取多少分钟的秒
    public static int getSecondByMinute(int date) {
        return minuteSecond * date;
    }


    static String verifyCodes = "1234567890";

    public static String getVerifyCode(int length) {
        String ret = "";
        int len = verifyCodes.length() - 1;
        for (int i = 0; i < length; i++) {
            int index = (int) (Math.random() * len);
            ret += verifyCodes.substring(index, index + 1);
        }
        return ret;
    }

    public static String getVerifyCode() {
        return getVerifyCode(4);
    }

    public static int getDayTimeStampEndTimestamp(int timestamp) {
        return dateToTimeStamp(timestamp2DataStr(timestamp), "yyyy-MM-dd") + 86400;
    }

    /**
     * 时间戳 精确到秒 转日期格式的字符串,默认yyyy-MM-dd
     */
    public static String timestamp2DataStr(int i) {
        return timestamp2DataStr(i, "yyyy-MM-dd");
    }

    public static String timestamp2DataStr(int i, String format) {
        SimpleDateFormat sdff = new SimpleDateFormat(format);
        return sdff.format(new Date(i * 1000L));
    }

    /**
     * 通过身份证号获取生日和性别
     *
     * @param identifyNumber
     * @return
     */
    public static String[] getBirthAndSexByIdNo(String identifyNumber) {

        String dateOfBirth = null;

        String gender = null;

        //通过身份证获取性别和生日
        if (!isBlank(identifyNumber)) {

            if (identifyNumber.length() == 15) {

                dateOfBirth = "19" + identifyNumber.substring(6, 8) + "-" + identifyNumber.substring(8, 10) + "-" + identifyNumber.substring(10, 12);

                gender = identifyNumber.substring(14, 15);

                /*基数为男 偶数为女*/
                if (Integer.parseInt(gender) % 2 == 0) {
                    gender = "2";
                } else {
                    gender = "1";
                }
            } else if (identifyNumber.length() == 18) {
                dateOfBirth = identifyNumber.substring(6, 10) + "-" + identifyNumber.substring(10, 12) + "-" + identifyNumber.substring(12, 14);

                gender = identifyNumber.substring(16, 17);

                /*基数为男 偶数为女*/
                if (Integer.parseInt(gender) % 2 == 0) {
                    gender = "2";
                } else {
                    gender = "1";
                }
            }
        }

        String[] strings = new String[]{dateOfBirth, gender};

        return strings;
    }

    /**
     * 判断操作系统是否是Windows
     *
     * @return
     */
    public static boolean isWindowsOS() {
        boolean isWindowsOS = false;
        // 注：这里的system，系统指的是 JRE (runtime)system，不是指 OS
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().indexOf("windows") > -1) {
            isWindowsOS = true;
        }
        return isWindowsOS;
    }

    /**
     * 获取Linux下的IP地址
     *
     * @return IP地址
     * @throws SocketException
     */
    private static String getLinuxLocalIp() throws SocketException {
        String ip = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                String name = intf.getName();
                if (!name.contains("docker") && !name.contains("lo")) {
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipaddress = inetAddress.getHostAddress().toString();
                            if (!ipaddress.contains("::") && !ipaddress.contains("0:0:")
                                    && !ipaddress.contains("fe80")) {
                                ip = ipaddress;
                            }
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            ip = "127.0.0.1";
            ex.printStackTrace();
        }
        return ip;
    }

    public static String getLocalIP() {
        try {
            if (isWindowsOS()) {
                return InetAddress.getLocalHost().getHostAddress();
            } else {
                return getLinuxLocalIp();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "192.168.88.88";

    }

    public static List<String> duplicateRemovalList(List<String> list) {
        HashSet<String> strings = new HashSet<>();
        for (String l : list) {
            strings.add(l);
        }
        ArrayList<String> strings1 = new ArrayList<>();
        for (String l : strings) {
            strings1.add(l);
        }
        return strings1;
    }
}